from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from django.utils.decorators import method_decorator
from tools.logging_dec import logging_check, get_user_by_request
# from tools.cache_dec import cache_set
import json
from .models import Topic
from user.models import UserProfile
from django.http import QueryDict
from message.models import Message


# Create your views here.

class TopicViews(View):

    def make_topic_res(self, author, author_topic, is_self):    # , is_self

        if is_self:
            # 博主访问自己
            next_topic = Topic.objects.filter(id__gt=author_topic.id, author=author).first()
            last_topic = Topic.objects.filter(id__lt=author_topic.id, author=author).last()
        else:
            # 游客访问
            next_topic = Topic.objects.filter(id__gt=author_topic.id, author=author, limit='public').first()
            last_topic = Topic.objects.filter(id__lt=author_topic.id, author=author, limit='public').last()
        next_id = next_topic.id if next_topic else None
        next_title = next_topic.title if next_topic else ''
        last_id = last_topic.id if last_topic else None
        last_title = last_topic.title if last_topic else ''

        # 关联文章回复数据
        all_message = Message.objects.filter(topic=author_topic).order_by('-created_time')

        msg_list = []
        rep_dic = {}
        m_count = 0
        for msg in all_message:
            if msg.parent_message:
                # 回复
                rep_dic.setdefault(msg.parent_message, [])
                rep_dic[msg.parent_message].append({'msg_id': msg.id, 'publisher': msg.publisher.nickname, 'publisher_avatr': str(msg.publisher.avatar), 'content': msg.content, 'created_time': msg.created_time.strftime('%Y-%m-%d %H:%M:%S')})

            else:
                # 留言
                m_count += 1
                msg_list.append({'id': msg.id, 'content': msg.content, 'publisher': msg.publisher.nickname, 'publisher_avatr': str(msg.publisher.avatar), 'created_time': msg.created_time.strftime('%Y-%m-%d %H:%M:%S'), 'reply':[]})

        for m in msg_list:
            if m['id'] in rep_dic:
                m['reply'] = rep_dic[m['id']]


        res = {'code': 200, 'data': {}}
        res['data']['nickname'] = author.nickname
        res['data']['title'] = author_topic.title
        res['data']['category'] = author_topic.category
        res['data']['created_time'] = author_topic.created_time.strftime('%Y-%m-%d %H:%M:%S')
        res['data']['content'] = author_topic.content
        res['data']['introduce'] = author_topic.introduce
        res['data']['author'] = author.nickname
        res['data']['last_id'] = last_id   # last_id
        res['data']['last_title'] = last_title  # last_title
        res['data']['next_id'] = next_id   # next_id
        res['data']['next_title'] = next_title    # next_title
        res['data']['messages'] = msg_list
        res['data']['messages_count'] = m_count
        return res
    #
    def make_topics_res(self, author, author_topics):

        res = {'code': 200, 'data': {}}
        topics_res = []
        for topic in author_topics:
            d = {}
            d['id'] = topic.id
            d['title'] = topic.title
            d['category'] = topic.category
            d['create_time'] = topic.created_time.strftime("%Y-%m-%d%H:%M:%S")
            d['introduce'] = topic.introduce
            d['author'] = author.nickname
            topics_res.append(d)
        res['data']['topics'] = topics_res
        res['data']['nickname'] = author.nickname
        return res

# 发表文章页的逻辑
    @method_decorator(logging_check)
    def post(self, request, author_id):
        # 创建数据

        author = request.myuser
        print('author')
        # 取出前端数据
        json_str = request.body
        json_obj = json.loads(json_str)
        title = json_obj['title']
        content = json_obj['content']
        content_text = json_obj['content_text']
        introduce = content_text[:30]
        limit = json_obj['limit']
        category = json_obj['category']
        if limit not in ['public', 'private']:
            result = {'code': 10300, 'error': 'limit error'}
            return JsonResponse(result)

        # 创建Topic数据
        Topic.objects.create(title=title, content=content, limit=limit, introduce=introduce, category=category,author=author)
        return JsonResponse({'code': 200})


    # @method_decorator(cache_set(300))
    def get(self, request, author_id):
        # print('------view------')
        # 访问者：visitor       被访问者：author
        # 尝试从 user数据库中取信息
        try:
            author = UserProfile.objects.get(username=author_id)
        except Exception as e:
            result = {'code': 10311, 'error': 'The author is not existed'}
            return JsonResponse(result)
        # 获取游客名
        visitor = get_user_by_request(request)  # 跳get_user_by_request
        # 给游客名一个默认值None
        visitor_username = None
        # 判断游客名是否存在
        if visitor:
            visitor_username = visitor.username

        t_id = request.GET.get('t_id')
        if t_id:
            # 获取指定文件数据
            t_id = int(t_id)
            is_self = False
            if visitor_username == author_id:
                is_self = True
                try:
                    author_topic = Topic.objects.get(id=t_id, author_id=author_id)
                except Exception as e:
                    result = {'code': 100302, 'error': 'No topic'}
                    return JsonResponse(result)
            else:
                try:
                    author_topic = Topic.objects.get(id=t_id, author_id=author_id, limit='public')
                except Exception as e:
                    result = {'code': 100303, 'error': 'No topic'}
                    return JsonResponse(result)

            res = self.make_topic_res(author, author_topic, is_self)   # , is_self
            return JsonResponse(res)


        else:
            # 获取列表页数据
            # 取category
            category = request.GET.get('category')
            if category in ['tec', 'no-tec']:
                # 如果author_id=visitor_username,可访问所有博客。=则只能访问开放的博客
                if visitor_username == author_id:
                    author_topics = Topic.objects.filter(author_id=author_id, category=category)
                else:
                    author_topics = Topic.objects.filter(author_id=author_id, limit='public', category=category)
            else:
                if visitor_username == author_id:
                    author_topics = Topic.objects.filter(author_id=author_id)
                else:
                    author_topics = Topic.objects.filter(author_id=author_id, limit='public')

            res = self.make_topics_res(author, author_topics)
            return JsonResponse(res)


    def delete(self, request, author_id):
        # json_str = request.body
        # json_obj = json.loads(json_str)
        # del_id = json_obj['delete_id']
        # del_id = int(del_id)
        t_id = request.GET.get('t_id')
        # tt_id = int(t_id)

        # DELETE = QueryDict(request.GET)
        # t_id = DELETE.get('t_id')

        try:
            orm_content = Topic.objects.filter(id=t_id, author_id=author_id)
        except Exception as e:
            result = {'code': 100304, 'error': 'not content'}
        if orm_content:
            # Topic.objects.delete(id=t_id, author_id=author_id)
            orm_content.delete()
        else:
            result = {'code': 100305, 'error': 'the content not exised'}
        res = {'code': 200, 'data': t_id}
        return JsonResponse(res)



    def put(self,request,author_id):
        json_str = request.body
        json_obj = json.loads(json_str)
        category = json_obj['category']
        limit = json_obj['limit']
        content_text = json_obj['content_text']
        title = json_obj['title']
        # t_id = json_obj['t_id']
        # try:
        #     update_data = Topic.objects.filter(author_id=author_id, id=t_id)
        # except Exception as e:
        #     result = {'code': 100304, 'error': 'No topic'}
        #     return JsonResponse(result)
        #
        # if limit not in ['public', 'private']:
        #     result = {'code': 10300, 'error': 'limit error'}
        #     return JsonResponse(result)
        # update_data.category = category
        # update_data.limit = limit
        # update_data.content = content_text
        # update_data.title = title
        # update_data.save()

        # Topic.objects.create(title=title, limit=limit, category=category, content_text=content_text)

        data_update = {'category': category, 'content_text': content_text, 'title': title, 'limit': limit}
        res = {'code': '200', 'data': data_update}
        # res = {'code': '200'}
        return JsonResponse(res)


def info_topic(request, author_id, t_id):

    # author_id = request.Get.get(author_id)
    # t_id = request.Get.get(t_id)
    #
    # topics_info = Topic.objects.filter(author_id=author_id, id=t_id)
    # category = topics_info.category
    # limit = topics_info.limit
    # content_text = topics_info.content_text
    # title = topics_info.title
    #
    #
    # data = {'category': category, 'content_text': content_text, 'title': title, 'limit':limit}
    # res = {'code': '200', 'data': data}
    res = {'code': '200'}
    return JsonResponse(res)


# def topic_info(request, topics_info):
#     res = {'code': 200, 'data': {}}
#     for d in topics_info:
#         d = {}
#         d['category'] = topic_info.category
#         d['limit'] = topic_info.limit
#         d['content_text'] = topic_info.content
#         d['title'] = topic_info.title
#     res['data'][]


